#include "conn_monitor.h"
#include "common.h"

#include <unistd.h>
// inotify headers
#include <stdio.h>
#include <errno.h>
#include <sys/inotify.h>
#include <sys/types.h>

conn_monitor* conn_monitor::instance = 0;

conn_monitor* conn_monitor::get_instance(){
    if (instance == NULL){
        instance = new conn_monitor;
    }
    return instance;
}

void conn_monitor::destroy(){
    if (instance != NULL){
        delete instance;
        instance = NULL;
    }
}

conn_monitor::conn_monitor() : in_fd(-1) {
}

conn_monitor::~conn_monitor(){

}

int conn_monitor::init(){

}

int conn_monitor::add_watch(const char* file_name){
    int ret = inotify_add_watch(in_fd, file_name, IN_ALL_EVENTS);
    LOGI("add_watch %d %s ret=%d", in_fd, file_name, ret);
    return ret;
}

int conn_monitor::remove_watch(const char* file_name){

}

void conn_monitor::run(){

    int ret = -1;

    in_fd = inotify_init();
    LOGI("inotify_init ret=%d, errno=%d", in_fd, errno);
    if (in_fd < 0){
        return;
    }

    while(true){
        LOGI("loop\n");

        char buffer[4096] = {0};
        ret = read(in_fd, buffer, sizeof(buffer));
        if (ret < 0){
            break;
        }

        struct inotify_event* evt_ptr;
        evt_ptr = (struct inotify_event*)buffer;

        int wd = evt_ptr->wd;
        uint32_t mask = evt_ptr->mask;
        uint32_t cookie = evt_ptr->cookie;
        uint32_t len = evt_ptr->len;

        if (mask & IN_UNMOUNT
            || mask & IN_IGNORED
            || mask & IN_Q_OVERFLOW
            || mask & IN_MOVE_SELF
            || mask & IN_DELETE_SELF){
            LOGI("watch was removed!\n");
            /*ret = inotify_add_watch(fd, "../a", IN_ALL_EVENTS);
            if (ret < 0){
            LOGI("add watch error! %d\n", errno);
            return;
            }*/
        }


        LOGI("file has changed wd=%d mask=%x cookie=%u len=%u", wd, mask, cookie, len);

    }
    LOGI("inotify exit!\n");
}
